<?php
//+-------------------------------------------------------------
//| sevice基类，留作扩展之用
//| 一个业务方法函数模板
//| /**
//|  * xxx函数功能说明
//|  * @param int $id
//|  * @return bool
//|  */
//| public function xxx($id)
//| {
//|     Db::startTrans();
//|     try{
//|         /*业务逻辑*/
//|         Db::commit();
//|         return true;
//|     }catch (\Exception $ex){
//|         Db::rollback();
//|         $this->catchError($ex);
//|     }
//|     return false;
//|  }
//|
//+-------------------------------------------------------------
//| Author Liu LianSen <liansen@d3zz.com> 
//+-------------------------------------------------------------
//| Date 2017-09-06
//+-------------------------------------------------------------
namespace app\common\service;
use app\appclient\Error;
use app\sys\model\SysUser;
use think\exception\PDOException;


/**
 *
 *
 * @author Liu LianSen <liansen@d3zz.com>
 * @since 2017-09-06
 */
class Service
{

    protected $code = 200;

    /**
     * @var string 最后的错误信息
     */
    protected $lastError = '';

    /**
     * 获取状态码
     * @return int
     */
    public function getCode()
    {
        return $this->code;
    }


    /**
     * 获取最后错误信息
     * @return string
     */
    public function getLastError()
    {
        return $this->lastError;
    }


    /** 设置错误信息
     * @param string $error
     */
    protected function setLastError($error)
    {
        $this->lastError = $error;
    }


    /**
     * 获取token对应的用户
     * @param $token
     * @param array $width
     * @param bool $cache
     * @return bool|SysUser
     */
    public function getTokenUser($token,$width = [],$cache = false)
    {
        $user = SysUser::get(['token' => $token], $width, $cache);
        return $user ?: $this->tokenNotExists();
    }

    /**
     * 设置token不存在时的code和错误信息
     * @return bool
     */
    public function tokenNotExists()
    {
        $this->code = Error::NOT_FOUND_CODE;
        $this->lastError = Error::TOKEN_INVALID_MSG;
        return false;
    }

    /**
     * 捕获异常信息做为当前code和error信息，并且记录错误
     * @param \Exception $ex
     */
    public function catchError(\Exception $ex)
    {
        if($ex instanceof  PDOException){
            $code = Error::SERVER_ERROR_CODE;
            $message = Error::SERVER_BUSY_MSG;
        }else{
            $code = intval($ex->getCode());
            $message = $ex->getMessage();
            if($code == 0){
                $code = Error::SERVER_ERROR_CODE;
                $message = Error::SERVER_BUSY_MSG;
            }
        }
        error($ex);
        $this->code = $code;
        $this->lastError = $message;
    }


}
